<template>
    <div class="home">
        <div class="cup" @click="openPopupHandler">
            <div class="cup-body">
                <div :class="`cup-body-layer ${item.styles}`" :key="`coffee_${index}`"
                    v-for="(item, index) in coffeeDosings">
                    {{ item.name }}
                </div>
            </div>
            <div class="cup-left-dark"></div>
            <div class="cup-right-dark"></div>
        </div>
        <pop-up title="选择配料表" v-model:open="openPopup">
            <coffee-dosing v-model:coffee="coffee" />
        </pop-up>
        <shop-cart :coffee="coffeeDosings" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onActivated } from "vue";
import PopUp from "@/components/Popup/index.vue";
import ShopCart from "./components/ShopCart/index.vue";
import CoffeeDosing from "./components/Dosing/index.vue";
import type { ICoffeeProps, ICoffeeDosingProps, getArrayItemType } from "@/types";
import useGlobalStore from "@/store/useGlobalStore";
import HttpService from "@/core/HttpService";

defineOptions({ name: "home" });

export interface ICoffeeType extends ICoffeeProps {
    children: Array<ICoffeeDosingProps & { checked?: boolean; }>
}

export type ISelectCoffeeType = getArrayItemType<ICoffeeProps["children"] & { pid: string; ptitle: string; }>;

const globalStore = useGlobalStore();

const getHttpData = ()=>{
    HttpService.get("http://47.92.125.130:9088/room/list",{type: 4}).then(res=>{
        console.log(res,"xxx");
    })
}

const defaultCoffee: Array<ICoffeeType> = [
    { id: "1", sub: "分类一", children: [{ id: "1-1", name: "美式咖啡", styles: "one", price: 12.5 }, { id: "1-2", name: "中式咖啡", styles: "one", price: 15.5 }] },
    { id: "2", sub: "分类二", children: [{ id: "2-1", name: "拿铁咖啡", styles: "two", price: 10 }] },
    { id: "3", sub: "分类三", children: [{ id: "3-1", name: "卡布奇诺", styles: "three", price: 15.99 }] }
];

const coffee = ref<Array<ICoffeeType>>([...defaultCoffee])


const coffeeDosings = computed<Array<ISelectCoffeeType>>(() => {
    const res: ICoffeeType["children"] = [];
    for (let i = 0; i < coffee.value.length; i++) {
        const { id, sub, children } = coffee.value[i];
        const item = children.find(op => op.checked);
        if (item) {
            Object.assign(item, { pid: id, ptitle: sub })
            res.push(item);
        }
    }
    return res;
})

const openPopup = ref<boolean>(false);

const openPopupHandler = () => openPopup.value = true;

onActivated(() => {
    if(!globalStore.keepAliveHome){
        coffee.value = [...defaultCoffee];
    }
})

</script>

<style lang="less" scoped>
@import "./index.less";
</style>